package com.danhar.forward.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * 发送Http请求工具类
 *
 * @author wu
 * @version 1.0
 * @date 2020/6/23/023
 */
public class HttpUtil {
    private final static String encoding = "utf-8";

    public static String sendGet(String url, JSONObject json, String token) {
        String param = StringUtil.jsonToString(json);
        String result = HttpRequest.get(url)
                .header("auth-token", token)
                .header("Content-type", "application/json")
                .charset(encoding)
                .body(param)
                .execute().body();
        return result;
    }

    public static String sendPost(String url, JSONObject json, String token) {
        String param = StringUtil.jsonToString(json);
        System.out.println("请求参数为：" + json);
        System.out.println("您当前访问的路径是：" + url);
        String result = HttpRequest.post(url)
                .header("auth-token", token)
                .header("Content-type", "application/json")
                .charset(encoding)
                .body(param)
                .execute().body();
        return result;
    }

    /**
     * 文件上传
     * @param url
     * @param multipartFile
     * @param fileParName
     * @param params
     * @param timeout
     * @param token
     * @return
     */
    public static Map<String, String> sendMultipartFilePost(String url, MultipartFile multipartFile, String fileParName,
                                                            Map<String, Object> params, int timeout,String token) {
        Map<String, String> resultMap = new HashMap<String, String>();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            String fileName = null;
            fileName = multipartFile.getOriginalFilename();
            builder.addBinaryBody(fileParName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流

            //解决中文乱码
            ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
            if(params!=null&&params.size()>0){
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    if(entry.getValue() == null)
                        continue;
                    // 类似浏览器表单提交，对应input的name和value
                    builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
                }
            }

            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);

            //String  token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHQiOjE1OTMwNjIyMjQxNTcsInRva2VuX3R5cGUiOjIsInVzZXJfaWQiOjh9.VkWaTU8udML8_PIIbgbFpaE1umnJ8Am--jq9NUK7E2w";
            httpPost.addHeader("auth-token",token);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交

            // 设置连接超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                    .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
            httpPost.setConfig(requestConfig);

            HttpEntity responseEntity = response.getEntity();
            resultMap.put("scode", String.valueOf(response.getStatusLine().getStatusCode()));
            resultMap.put("data", "");
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, java.nio.charset.Charset.forName("UTF-8"));
                resultMap.put("data", result);
            }
        } catch (Exception e) {
            resultMap.put("scode", "error");
            resultMap.put("data", "HTTP请求出现异常: " + e.getMessage());

            Writer w = new StringWriter();
            e.printStackTrace(new PrintWriter(w));
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultMap;
    }




}
